package cn.allms.boot.common.utils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件处理工具
 *
 * @author xieya
 * @date 2021/8/27
 */
public class PathUtils {
    /**
     * 创建文件夹，存在则不处理，不存在则创建
     * 注意，不能存在同名文件
     * @param dirName 绝对路径或相对路径
     */
    public static void createDirectory(String dirName) {
        Path path = Paths.get(dirName);
        if (Files.notExists(path)) {
            try {
                Path directory = Files.createDirectory(path);
                // 绝对路径
                System.out.println(directory.toAbsolutePath().toString());
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    /**
     * 创建文件夹，存在则不处理，不存在则创建
     * 注意，不能存在同名文件夹
     * @param fileName  文件名
     */
    public static void createFile(String fileName) {
        Path path = Paths.get(fileName);
        if (Files.notExists(path)) {
            try {
                Path file = Files.createFile(path);
                // 绝对路径
                System.out.println(file.toAbsolutePath().toString());
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    /**
     * 删除文件或文件夹
     * @param pathName 文件路径：目录或文件夹，相对路径或绝对路径均可
     */
    public static void deleteDirOrFile(String pathName){
        Path path = Paths.get(pathName);
        try {
            if (Files.deleteIfExists(path)) {
                //成功
                System.out.println("成功");
            }else{
                // 失败：不存在文件夹或文件
                System.out.println("失败：不存在文件夹或文件");
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    public static void copyFile(String sourcePath, String targetPath){
        Path source = Paths.get(sourcePath);
        Path target = Paths.get(targetPath);
        if(Files.exists(source) && Files.notExists(target)) {
            try {
                Path copy = Files.copy(source, target);
                System.out.println(copy.toAbsolutePath().toString());
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }


    public static void moveFile(String sourcePath, String targetPath){
        Path source = Paths.get(sourcePath);
        Path target = Paths.get(targetPath);
        if(Files.exists(source) && Files.notExists(target)) {
            try {
                Path copy = Files.move(source, target);
                System.out.println(copy.toAbsolutePath().toString());
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
}
